//
//  functions.cpp
//  Prism
//
//  Created by Bas du Pre on 24-05-11.
//  Copyright 2011 UU. All rights reserved.
//

#include "functions.h"
#include "PString.h"

#include <assert.h>
#include <sys/types.h>
#if PRISM_OS_WIN == 0
#include <unistd.h>
#include <sys/sysctl.h>
#endif

using namespace Prism;

PInt pRound (PFloat x) { 
  int i = (PInt) x; 
  if (x >= 0.0) { 
    return ((x-i) >= 0.5) ? (i + 1) : (i); 
  } else { 
    return (-x+i >= 0.5) ? (i - 1) : (i); 
  } 
} 

PFloat modulus(PFloat a, PFloat b)
{
    int result = static_cast<int>( a / b );
    return a - static_cast<PFloat>( result ) * b;
}

#if PRISM_OS_WIN == 0
// works only for bsd
bool posix_isDebuggerPresent(void)
// Returns true if the current process is being debugged (either 
// running under the debugger or has a debugger attached post facto).
{
    #if PRISM_OS_MAC || PRISM_OS_IOS
    int                 junk;
    int                 mib[4];
    struct kinfo_proc   info;
    size_t              size;
    
    // Initialize the flags so that, if sysctl fails for some bizarre 
    // reason, we get a predictable result.
    
    info.kp_proc.p_flag = 0;
    
    // Initialize mib, which tells sysctl the info we want, in this case
    // we're looking for information about a specific process ID.
    
    mib[0] = CTL_KERN;
    mib[1] = KERN_PROC;
    mib[2] = KERN_PROC_PID;
    mib[3] = getpid();
    
    // Call sysctl.
    
    size = sizeof(info);
    junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
    assert(junk == 0);
    
    // We're being debugged if the P_TRACED flag is set.
    
    return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
    #endif
    ///\todo: linux
    return false;
}
#endif

Prism::String objectToString(Prism::PObject *object) {
    return object->toString();
}

Prism::String objectToString(Prism::PObject object) {
    return object.toString();
}

Prism::String objectToString(Prism::String *object) {
    return *object;
}

Prism::String objectToString(Prism::String object) {
    return object;
}

